# !/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import xml.dom.minidom
import shutil


def getDocPaths(dir_name):
    # txt file

    filepathList = []

    for maindir, subdir, fileListStr in os.walk(dir_name):
        fileList = []
        for each in fileListStr:
            try:
                file_number = int(each[:-4])
                fileList.append(file_number)
            except:
                print('Ignore <%s>' % each)

        for each in sorted(fileList):
            filename = str(each) + '.xml'
            filepath = os.path.join(maindir, filename)
            filepathList.append(filepath)

    print("Dir <%s> has %d files." % (maindir, len(filepathList)))

    return filepathList


def parseXML(filepath):
    print("******Parsing <%s>******" % filepath)
    points = []
    DOMTree = xml.dom.minidom.parse(filepath)
    collection = DOMTree.documentElement

    if collection.getElementsByTagName('node'):
        nodes = collection.getElementsByTagName('node')

        for node in nodes:
            lon = node.getAttribute("lon")
            lat = node.getAttribute("lat")
            point = [lon, lat]
            points.append(point)

    else:
        print("Empty file, no node.")

    return points


def writeXML(points, file_path):
    print('Writing XML')
    doc = xml.dom.minidom.Document()
    doc.appendChild(doc.createComment("Generated by python, Author: Mengze."))
    osmNode = doc.createElement("osm")
    doc.appendChild(osmNode)

    addNode(doc, osmNode, points)

    print(file_path)

    with open(file_path, 'w') as f:
        doc.writexml(f, addindent="    ", newl="\n", encoding="UTF-8")

    print('Done!')


def addNode(doc, osmNode, points):

    for i, point in enumerate(points):
        if i == 0 or i == len(points) - 1 or i % 3 == 0:
            lon = point[0]
            lat = point[1]
            pointNode = doc.createElement("node")
            pointNode.setAttribute('lat', lat)
            pointNode.setAttribute('lon', lon)
            osmNode.appendChild(pointNode)


if __name__ == "__main__":

    ws_dir_path = "/home/mengze/Desktop/changsha_May20"

    input_dir = os.path.join(ws_dir_path, "seg")
    output_dir = ws_dir_path + "_sparse"

    if not os.path.isdir(output_dir):
        print('Make dir <%s>.' % output_dir)
        os.mkdir(output_dir)

    else:
        print('Delete and make new dir <%s>.' % output_dir)
        shutil.rmtree(output_dir)
        os.mkdir(output_dir)

    filepaths = getDocPaths(input_dir)

    # print(filepaths)
    for each in filepaths:
        each_filename = os.path.basename(each)
        output_path = os.path.join(output_dir, each_filename)

        points = parseXML(each)
        writeXML(points, output_path)
